from appium import webdriver
from appium.webdriver.common.appiumby import AppiumBy
from appium.webdriver.common.touch_action import TouchAction
from selenium.common import NoSuchElementException


class BasePage:

    def __init__(self, base_driver=None):
        self._IMPLICI_WAIT = 10
        if base_driver:
            self.driver = base_driver
        else:
            # 实例化driver
            caps = {"platformName": "Android",
                    "appPackage": "com.xueqiu.android",
                    "appActivity": ".view.WelcomeActivityAlias",
                    "deviceName": "127.0.0.1:7555",
                    "noReset": True,
                    "ensureWebviewsHavePages": True}

            self.driver = webdriver.Remote("http://127.0.0.1:4723/wd/hub", caps)
            self.driver.implicitly_wait(self._IMPLICI_WAIT)

    # 查找元素并返回元素对象
    def do_find(self, by, num=4):
        """
        查找元素并返回元素对象
        :return:
        """
        self.driver.implicitly_wait(5)
        for i in range(num):
            try:
                # 每次都浪费 15秒
                ele = self.driver.find_element(*by)
                # 找到就设置回原来的隐式等待时长
                self.driver.implicitly_wait(self._IMPLICI_WAIT)
                return ele
            except:
                # ?? 滑动
                # 当前屏幕的尺寸，完成滑动
                size = self.driver.get_window_size()
                width = size['width']
                height = size['height']
                startx = width / 2
                starty = height * 0.5
                endx = startx
                endy = 0
                duration = 1000
                self.driver.swipe(startx, starty, endx, endy, duration)
            if i == num - 1:
                self.driver.implicitly_wait(self._IMPLICI_WAIT)
                raise NoSuchElementException(f"找了{num}次，未找到元素{by}")

    def do_finds(self, by):
        """
        查找多个元素并返回元素对象列表
        :return:
        """
        return self.driver.find_elements(*by)

    def do_click(self, by):
        """
        点击元素
        :param by:
        :return:
        """
        self.do_find(by).click()
        return self

    def do_send_keys(self, by, value):
        """
        输入操作
        :param by: 定位方式和定位值的元祖
        :param value: 要输入的值
        :return:
        """
        ele = self.do_find(by)
        # 先清空输入框，在进行输入内容
        ele.clear()
        ele.send_keys(value)

    def do_quit(self):
        """
        关闭浏览器
        :return:
        """
        self.driver.quit()


